package com.personnelsystem;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DatabaseConnection {
    DataSource dataSource;
    //生成一个连接池对象
    public DatabaseConnection() {
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("F:\\Java-idea\\chapter5\\src\\com\\personnelsystem\\druid.properties");
        } catch (FileNotFoundException e) {
            System.err.println("没有这个文件！");
            e.printStackTrace();
        }
        try {
            properties.load(inputStream);
        } catch (Exception e) {
            System.err.println("读取配置失败");
            e.printStackTrace();
        }
        try {
            dataSource = new DruidDataSourceFactory().createDataSource(properties);
        } catch (Exception e) {
            System.err.println("创建连接池失败");
            e.printStackTrace();
        }
        System.out.println("创建连接池成功");
    }

    public Connection getConnetion() throws SQLException {
        //从池中获取连接
        System.out.println("从连接池得到一条连接");
        return dataSource.getConnection();
    }

}
